#include "tcpserver.h"
#include <QMessageBox>
#include <QDebug>

TcpServer::TcpServer(QObject *parent) : QObject(parent)
{
    mServer=new QTcpServer(this);
    if(mServer->listen(QHostAddress::Any,12306)==false)
        {
            QMessageBox::critical(0,"错误","不能打开监听端口:12306");
                    exit(-1);
        }
    mServer->setMaxPendingConnections(100);
    connect(mServer,SIGNAL(newConnection()),this,SLOT(onNewConnection()));

}

TcpServer* TcpServer::m_pInstance=NULL;
TcpServer* TcpServer::getInstanse()
{
    if(m_pInstance==NULL)
        {
            m_pInstance=new TcpServer(0);
        }
    return m_pInstance;
}

void TcpServer::onNewConnection()
{
    qDebug()<<"connect+1";
    QTcpSocket *client=mServer->nextPendingConnection();

    if(client!=NULL){
            ClientHandler *handler = new ClientHandler(client,this);

            connect(handler,SIGNAL(received(const QByteArray &,QTcpSocket*)),this,SIGNAL(received(const QByteArray &,QTcpSocket*)));

            m_clientlist.append(handler);
        }
}


void TcpServer::writeToClients(const QByteArray &data)
{
    ClientHandler *client;
    foreach(client,m_clientlist)
    {
        client->write(data);
    }
}

TcpServer::~TcpServer()
{
    delete mServer;
}


//QTcpSocket* TcpServer::socketSender()
//{
//    QTcpSocket* client=(QTcpSocket*)this->sender();
//    if(client!=NULL)
//       return client;
//}
